<template>
  <div class="cosmic-input-container" :class="{ 'has-focus': isFocused, 'has-error': error }">
    <div class="starfield-background" ref="starfieldRef"></div>
    <div class="input-wrapper">
      <input
        v-if="!textarea"
        :type="type"
        :value="modelValue"
        @input="updateValue"
        @focus="onFocus"
        @blur="onBlur"
        :placeholder="placeholder"
        class="cosmic-input"
        :disabled="disabled"
        :required="required"
        :name="name"
        :id="id"
        autocomplete="on"
      />
      <textarea
        v-else
        :value="modelValue"
        @input="updateValue"
        @focus="onFocus"
        @blur="onBlur"
        :placeholder="placeholder"
        class="cosmic-input cosmic-textarea"
        :disabled="disabled"
        :required="required"
        :name="name"
        :id="id"
        :rows="rows || 3"
        autocomplete="on"
      ></textarea>
      <div class="floating-label" :class="{ 'active': isFocused || modelValue }">
        {{ label }}
      </div>
      <div v-if="icon" class="input-icon">
        <slot name="icon"></slot>
      </div>
    </div>
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as THREE from 'three'

export default {
  name: 'CosmicInput',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    label: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'text'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: false
    },
    error: {
      type: String,
      default: ''
    },
    icon: {
      type: Boolean,
      default: false
    },
    textarea: {
      type: Boolean,
      default: false
    },
    rows: {
      type: Number,
      default: 3
    },
    name: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'focus', 'blur'],
  setup(props, { emit }) {
    const starfieldRef = ref(null)
    const isFocused = ref(false)
    
    // Three.js相关变量
    let scene = null
    let camera = null
    let renderer = null
    let stars = null
    let animationId = null
    
    // 更新值
    const updateValue = (event) => {
      emit('update:modelValue', event.target.value)
    }
    
    // 聚焦处理
    const onFocus = (event) => {
      isFocused.value = true
      emit('focus', event)
      // 加速星星动画
      if (stars) {
        stars.userData.speed = 0.005
      }
    }
    
    // 失焦处理
    const onBlur = (event) => {
      isFocused.value = false
      emit('blur', event)
      // 减速星星动画
      if (stars) {
        stars.userData.speed = 0.001
      }
    }
    
    // 创建星空背景
    const createStarfield = () => {
      if (!starfieldRef.value) return
      
      // 设置容器尺寸
      const rect = starfieldRef.value.getBoundingClientRect()
      
      // 创建场景
      scene = new THREE.Scene()
      scene.background = new THREE.Color(0x0a0a2a)
      
      // 创建正交相机
      camera = new THREE.OrthographicCamera(
        rect.width / -2, 
        rect.width / 2, 
        rect.height / 2, 
        rect.height / -2, 
        1, 
        1000
      )
      camera.position.z = 100
      
      // 创建渲染器
      renderer = new THREE.WebGLRenderer({ 
        antialias: true, 
        alpha: true 
      })
      renderer.setSize(rect.width, rect.height)
      renderer.setPixelRatio(window.devicePixelRatio)
      renderer.domElement.style.position = 'absolute'
      renderer.domElement.style.top = '0'
      renderer.domElement.style.left = '0'
      renderer.domElement.style.pointerEvents = 'none'
      
      starfieldRef.value.appendChild(renderer.domElement)
      
      // 创建星星
      const starCount = 200
      const positions = new Float32Array(starCount * 3)
      const colors = new Float32Array(starCount * 3)
      const sizes = new Float32Array(starCount)
      
      for (let i = 0; i < starCount; i++) {
        // 随机位置
        const i3 = i * 3
        positions[i3] = (Math.random() - 0.5) * rect.width
        positions[i3 + 1] = (Math.random() - 0.5) * rect.height
        positions[i3 + 2] = Math.random() * 100
        
        // 随机颜色（主要是白色和淡蓝色）
        const colorType = Math.random()
        if (colorType < 0.7) {
          // 白色星星
          colors[i3] = colors[i3 + 1] = colors[i3 + 2] = 1.0
        } else if (colorType < 0.9) {
          // 淡蓝色星星
          colors[i3] = 0.8
          colors[i3 + 1] = 0.9
          colors[i3 + 2] = 1.0
        } else {
          // 金色星星
          colors[i3] = 1.0
          colors[i3 + 1] = 0.9
          colors[i3 + 2] = 0.5
        }
        
        // 随机大小
        sizes[i] = 0.5 + Math.random() * 2
      }
      
      // 创建几何体
      const geometry = new THREE.BufferGeometry()
      geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))
      geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3))
      geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1))
      
      // 创建材质
      const material = new THREE.PointsMaterial({
        size: 1,
        vertexColors: true,
        sizeAttenuation: true,
        transparent: true,
        opacity: 0.7,
        blending: THREE.AdditiveBlending
      })
      
      // 创建点云对象
      stars = new THREE.Points(geometry, material)
      stars.userData.speed = 0.001 // 默认速度
      scene.add(stars)
      
      // 开始动画
      animate()
    }
    
    // 动画循环
    const animate = () => {
      animationId = requestAnimationFrame(animate)
      
      if (stars) {
        // 缓慢旋转星空
        stars.rotation.z += stars.userData.speed
        
        // 星星闪烁效果
        if (stars.material.opacity > 0.5 && Math.random() > 0.98) {
          stars.material.opacity = 0.5 + Math.random() * 0.5
        } else if (Math.random() > 0.99) {
          stars.material.opacity = 0.7 + Math.random() * 0.3
        }
      }
      
      if (renderer && scene && camera) {
        renderer.render(scene, camera)
      }
    }
    
    // 调整大小
    const handleResize = () => {
      if (!starfieldRef.value || !renderer || !camera) return
      
      const rect = starfieldRef.value.getBoundingClientRect()
      
      camera.left = rect.width / -2
      camera.right = rect.width / 2
      camera.top = rect.height / 2
      camera.bottom = rect.height / -2
      camera.updateProjectionMatrix()
      
      renderer.setSize(rect.width, rect.height)
    }
    
    // 组件挂载时创建星空
    onMounted(() => {
      createStarfield()
      
      // 监听输入框尺寸变化
      const observer = new ResizeObserver(handleResize)
      if (starfieldRef.value) {
        observer.observe(starfieldRef.value)
      }
      
      // 清理函数
      onUnmounted(() => {
        if (observer && starfieldRef.value) {
          observer.unobserve(starfieldRef.value)
        }
      })
    })
    
    // 组件卸载时清理
    onUnmounted(() => {
      if (animationId) {
        cancelAnimationFrame(animationId)
      }
      
      if (renderer) {
        renderer.dispose()
        if (starfieldRef.value && renderer.domElement) {
          starfieldRef.value.removeChild(renderer.domElement)
        }
      }
      
      if (stars) {
        stars.geometry.dispose()
        stars.material.dispose()
      }
    })
    
    return {
      starfieldRef,
      isFocused,
      updateValue,
      onFocus,
      onBlur
    }
  }
}
</script>

<style scoped>
.cosmic-input-container {
  position: relative;
  margin-bottom: 20px;
  width: 100%;
}

.starfield-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  z-index: 0;
}

.input-wrapper {
  position: relative;
  z-index: 1;
}

.cosmic-input {
  width: 100%;
  padding: 14px 20px;
  padding-top: 22px;
  background: rgba(10, 10, 42, 0.6);
  border: 2px solid rgba(85, 136, 255, 0.3);
  border-radius: 8px;
  color: #ffffff;
  font-size: 16px;
  outline: none;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  box-sizing: border-box;
}

.cosmic-textarea {
  min-height: 100px;
  resize: vertical;
  font-family: inherit;
}

.cosmic-input:focus {
  border-color: #5588ff;
  box-shadow: 0 0 20px rgba(85, 136, 255, 0.3);
}

.cosmic-input:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.cosmic-input-container.has-error .cosmic-input {
  border-color: #ff5555;
}

.floating-label {
  position: absolute;
  left: 20px;
  top: 18px;
  color: rgba(255, 255, 255, 0.75);
  font-size: 16px;
  pointer-events: none;
  transition: all 0.2s ease;
  z-index: 2;
}

.floating-label.active {
  top: -10px;
  left: 16px;
  font-size: 12px;
  color: #5588ff;
  letter-spacing: 0.5px;
  text-shadow: 0 0 8px rgba(85, 136, 255, 0.6);
}

.input-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: rgba(255, 255, 255, 0.6);
  z-index: 2;
}

.error-message {
  position: absolute;
  bottom: -20px;
  left: 0;
  color: #ff5555;
  font-size: 12px;
  z-index: 1;
}

/* 焦点状态的容器效果 */
.cosmic-input-container.has-focus .starfield-background {
  box-shadow: 0 0 20px rgba(85, 136, 255, 0.4);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cosmic-input {
    font-size: 14px;
    padding: 12px 16px;
    padding-top: 20px;
  }
  
  .floating-label {
    font-size: 14px;
  }
  
  .floating-label.active {
    font-size: 11px;
  }
}
</style>